package com.ccdt.tv.smartrecommend.view.tools;

import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import com.blankj.utilcode.util.Utils;
import com.ccdt.tv.smartrecommend.view.bean.IntentEventBean;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;



/**
 * Created by wudz on 2017/9/7.
 */

public class OutEventBus {
    private static final String TAG="OutEventBus";
    private static OutEventBus instance;

    public static OutEventBus getInstance() {
        if (instance == null)
            instance = new OutEventBus();
        return instance;
    }
    public static IntentEventBean createSimpleEventBean(String packageName, String className)
    {
             return new IntentEventBean.Builder("","","",0).setClassName(className)
                .setPackageName(packageName).setAction(Intent.ACTION_VIEW).setIntentFlag(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP).build();
    }

    public boolean startEvent(IntentEventBean outerEventBean) {
        Log.i(TAG,"startEvent:v:"+outerEventBean);
        if(outerEventBean==null)
            return false;
//        if(TextUtils.isEmpty(outerEventBean.getId())==false
//                && (outerEventBean.getId().equals("e1")||
//                outerEventBean.getId().equals("e4")||outerEventBean.getSrcViewId().equals("MENU_0")))
//        {
//            Log.i(TAG,"startEvent:");
//            if(true== DvbVodInfoManager.openDvbPlayer(Utils.getApp()))
//                return true;
//        }
        if(outerEventBean instanceof IntentEventBean)
        {
            IntentEventBean intentEvent=(IntentEventBean)outerEventBean;
            int startType=((IntentEventBean) outerEventBean).getStartType();
            switch (startType)
            {
                case IntentEventBean.TYPE_STARTACTIVITY:
                case IntentEventBean.TYPE_SENDBROADCAST:
                case IntentEventBean.TYPE_COMMAND:
                    return start(intentEvent);
                case IntentEventBean.TYPE_STARTSERVICE:
                    return false;
            }
        }
        return false;
    }

    private boolean start(final IntentEventBean intentEventBean)
    {
        try {
            Intent intent=new Intent();
            setPackageAndActivity(intent,intentEventBean);
            setActionAndData(intent,intentEventBean);
            setFlag(intent,intentEventBean);
            setIntentExtry(intent,intentEventBean);
            int startType = intentEventBean.getStartType();
            switch (startType) {
                case IntentEventBean.TYPE_STARTACTIVITY:
                    //快速启动模式 忽略类名
                    if(intentEventBean.getClassName()==null||intentEventBean.getClassName().equals("")) {
                        Log.i(TAG,"start:fast mode!");
                        intent = Utils.getApp().getPackageManager().getLaunchIntentForPackage(intentEventBean.getPackageName());
                    }
                    Utils.getApp().startActivity(intent);
                    return true;
                case IntentEventBean.TYPE_SENDBROADCAST:
//                    Log.w(TAG, "start: 发送广播：action :"+intent.getAction() );
                    Utils.getApp().sendBroadcast(intent);
                    return true;
                case IntentEventBean.TYPE_STARTSERVICE:
                    Utils.getApp().startService(intent);
                    return true;
                case IntentEventBean.TYPE_COMMAND:
                    if(intentEventBean.getCommandLine()==null || intentEventBean.getCommandLine().equals(""))
                        return false;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            execWithSID(intentEventBean.getCommandLine());
                        }
                    });
                    return true;
            }
        }catch (Exception e)
        {
            Log.i(TAG,"onStartDraw is error!");
            e.printStackTrace();
        }
        return false;
    }
    private void setPackageAndActivity(Intent intent, IntentEventBean p)
    {
        if(p.getPackageName()!=null && !p.getPackageName().equals(""))
        {
            intent.setPackage(p.getPackageName());
            if(p.getClassName()!=null && !p.getClassName().equals(""))
            {
                intent.setClassName(p.getPackageName(),p.getClassName());
            }
        }

    }

    private void setActionAndData(Intent intent, IntentEventBean p)
    {
        if(p.getDataUri()!=null && !p.getDataUri().equals(""))
        {
            intent.setData(Uri.parse(p.getDataUri()));
        }
        if(p.getAction()!=null && !p.getAction().equals(""))
        {
            intent.setAction(p.getAction());
        }
    }

    private void setFlag(Intent intent, IntentEventBean p)
    {
        if (p.getFlag() != 0)
            intent.setFlags(p.getFlag());
    }

    private void setIntentExtry(Intent intent,IntentEventBean p)
    {
        HashMap<String, String> intentKV = p.getKeyValue();
        for (String key : intentKV.keySet()) {
//            intent.putExtra(key, OutEvetnKeyword.replaceKeyword(intentKV.get(key)));
            intent.putExtra(key, intentKV.get(key));
        }
        HashMap<String,Integer> intentKVI=p.getKeyValueInt();
        for (String keyI : intentKVI.keySet()) {
            intent.putExtra(keyI, intentKVI.get(keyI));
        }
        HashMap<String,Boolean> intentKVB=p.getKeyValueBoolean();
        for (String keyB : intentKVB.keySet()) {
            intent.putExtra(keyB, intentKVB.get(keyB));
        }
    }

    private static boolean execWithSID(String... args) {
        boolean isSuccess = false;
        Process process = null;
        OutputStream out = null;
        try {
            process = Runtime.getRuntime().exec("sh");
            out = process.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(out);

            for (int i = 0; i < args.length; i++) {
                dataOutputStream.writeBytes(args[i]);
            }

            dataOutputStream.flush(); // 提交命令
            dataOutputStream.close(); // 关闭流操作
            out.close();
            isSuccess = waitForProcess(process);
            Log.i(TAG, "execWithSID  result:" + isSuccess);
        } catch (IOException e) {
            Log.e(TAG, "execWithSID  failed!");
            e.printStackTrace();
        }

        return isSuccess;
    }
    private static boolean waitForProcess(Process p) {
        boolean isSuccess = false;
        int returnCode;
        try {
            returnCode = p.waitFor();
            switch (returnCode) {
                case 0:
                    isSuccess = true;
                    break;

                case 1:
                    break;

                default:
                    break;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return isSuccess;
    }
}
